package bob.project.object;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Shape;

import bob.project.slick.GameState;

public abstract class GameObject
{

	public int width;
	public int height;
	public float x;
	public float y;
	protected Shape shape;
	public boolean removed = false;
	public boolean onGround = false;
	public float gravity = 10f;
	public float ySpeed = 0;
	boolean canCollide = true;
	public String image;
	
	public void setDimensions(float xx,float yy, int width, int height)
	{
		x = xx;
		y = yy;
		this.width = width;
		this.height = height;
		shape = new Rectangle (x,y,width,height);
	}
	
	
	public abstract void update(int delta);

	
	public abstract void draw(Graphics g);
	
	public void gravityForce(int delta)
	{
		if (!onGround)
		{
			if (tryMoveTo(x,y+ySpeed/1000f*delta))
			{
				float oldSpeed = ySpeed;
				ySpeed+= gravity;
				if (ySpeed >= gravity*16)
					ySpeed = gravity*16;
				if (tryMoveTo(x,y+ySpeed/1000f*delta))
					y+=ySpeed/1000f*delta;
				else
					y+=oldSpeed/1000f*delta;
			}
			else
			{
				ySpeed = 0;
				onGround = true;
			}
		}
		else
		{
			if (tryMoveTo(x,y+1))
				onGround = false;
		}
		
	}
	
	public boolean tryMoveTo(float xx, float yy)
	{
		Rectangle newRect = new Rectangle(xx,yy,width,height-2);
		for(int i = 0; i < GameState.instance.objects.size();i++)
		{
			GameObject obj = GameState.instance.objects.get(i);
			if (obj instanceof Bullet || obj == this || obj instanceof ItemObject || !obj.canCollide)
				continue;
			if (obj instanceof LiveObject && ((LiveObject)obj).isDead)
				continue;
			if (obj.shape.intersects(newRect) && !obj.removed)
				return false;
		}
		return true;
	}
	
	public GameObject tryMove(float xx, float yy)
	{
		Rectangle newRect = new Rectangle(xx,yy,width,height-1);
		for(int i = 0; i < GameState.instance.objects.size();i++)
		{
			GameObject obj = GameState.instance.objects.get(i);
			if (obj instanceof ItemObject || obj == this || obj.removed || !obj.canCollide)
				continue;
			if (obj.shape.intersects(newRect))
				return obj;
		}
		return null;
	}
	
	public GameObject hitLive(float xx, float yy)
	{
		Rectangle newRect = new Rectangle(xx,yy,width,height-1);
		for(int i = 0; i < GameState.instance.objects.size();i++)
		{
			GameObject obj = GameState.instance.objects.get(i);
			if (!(obj instanceof LiveObject) || obj == this || !obj.canCollide)
				continue;
			if (obj.shape.intersects(newRect))
				return obj;
		}
		return null;
	}
}
